LeetCode Js-219. Contains Duplicate II
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
給予一個整數陣列 nums,和一個整數 k,如果有兩個重複值得索引 i 和 j 在這個陣列中,且符合以下條件,則回傳 true。
1. nums[i] == nums[j]
2. abs(i - j) <= k
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Solution:
1. 物件特性找出有出現過的數值。
2. 重複出現的數值索引 i 和 j,兩者之間的距離小於等於 k。
Code:
var containsNearbyDuplicate = function(nums, k) {
if (nums.length <= 1) return false //只有一個數值,條件不成立,故提前結束。
let box = {}
for (let i in nums) {
let j = nums[i]
if (box[j] && ((i - box[j]) <= k)) {
return true
}
box[j] = i
}
return false
};
FlowChart:
Example 1
Input: nums = [1,2,3,1], k = 3
nums.length = 4 >= 1
step.1
box = {}
i = 0, j = 1, box[1] = undefined => false |box[1] = 0 => {'1': 0}
i = 1, j = 2, box[2] = undefined => false |box[2] = 1 => {'1': 0, '2': 1}
i = 2, j = 3, box[3] = underfined => false |box[3] = 2 => {'1': 0, '2': 1, '3': 2}
i = 3, j = 1, box[1] && ((3 - box[1]) <= k)
// 0 && ((3 - 1) <= 3) => return true